import { goTo } from '../../utils/index';

Component({
  options: {
    styleIsolation: 'apply-shared'
  },
  properties: {
    title: {
      type: String,
      value: ''
    },
    titleBg: {
      type: String,
      value: ''
    },
    titleImg: {
      type: String,
      value: ''
    },
    noBack: {
      type: Boolean,
      value: false
    },
    onBack: Boolean
  },
  data: {
    show: true,
    titleTop: 0,
    titleHeight: 0,
    titlePadding: 0,
    backLeft: 0,
    backSize: 0,
    noHistory: false,
    bgImg: ''
  },
  observers: {
    titleImg: function(val) {
      this.setData({
        bgImg: val ? (val.indexOf('linear-gradient') > -1 ? val : 'url(' + val + ')') : 'none'
      });
    }
  },
  lifetimes: {
    attached() {
      const pages = getCurrentPages();
      const menu = wx.getMenuButtonBoundingClientRect();
      const sys = wx.getWindowInfo();
      const scale = sys.windowWidth / 375;

      this.setData({
        titleTop: menu.top * 2 / scale,
        titleHeight: menu.height * 2 / scale,
        titlePadding: (menu.width + sys.windowWidth - menu.right) * 2 / scale,
        titleBottom: 10,
        backLeft: (sys.windowWidth - menu.right) * 2 / scale,
        backSize: menu.height * 2 / scale,
        noHistory: pages.length <= 1
      });

      const {
        titleTop,
        titleHeight,
        titleBottom
      } = this.data;

      this.triggerEvent('topbar', {
        height: titleTop + titleHeight + titleBottom,
        menu: {
          bottom: menu.bottom * 2 / scale,
          height: menu.height * 2 / scale,
          left: menu.left * 2 / scale,
          right: (sys.windowWidth - menu.right) * 2 / scale,
          top: menu.top * 2 / scale,
          width: menu.width * 2 / scale,
        }
      });
    }
  },
  methods: {
    onBack() {
      const {
        noHistory,
        onBack
      } = this.data;

      if (onBack) {
        this.triggerEvent('back');
      } else if (noHistory) {
        wx.reLaunch({
          url: '/pages/index/index',
        })
      } else {
        wx.navigateBack({
          delta: 1
        });
      }
    }
  }
})